package com.example.racetracker.model

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.setValue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay

class RaceParticipant(
    val name: String,
    private val maxProgress: Int = 100,
    private val progressDelayMillis: Long = 500L,
    private val processIncrement: Int = 1,
    private val initialProgress: Int = 0
) {
    init {
        require(maxProgress > 0) { "maxProgress=$maxProgress; must be > 0" }
        require(processIncrement > 0) { "processIncrement=$processIncrement; must be > 0" }
    }

    var currentProgress by mutableIntStateOf(initialProgress)
        private set

    suspend fun run() {
        try {
            while (currentProgress < maxProgress) {
                currentProgress += processIncrement
                if (currentProgress > maxProgress) {
                    currentProgress = maxProgress
                }
                delay(progressDelayMillis)
            }
        } catch (e: CancellationException) {
            Log.e("RaceParticipant", "$name: ${e.message}")
            throw e
        }
    }

    fun reset() {
        currentProgress = 0
    }

    val processFactor: Float
        get() = currentProgress / maxProgress.toFloat()
}
